package ute.mvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.Course;
import ute.mvc.model.OpenCourse;
@Repository("courseDAO")
public class CourseDAOImpl implements CourseDAO{
	@Autowired
	SessionFactory sessionFactory;

	public void addCourse(Course course) {
		sessionFactory.getCurrentSession().save(course);
	}
	
	@SuppressWarnings("unchecked")
	public List<Course> getAllCourse() {
		return sessionFactory.getCurrentSession()
				.createCriteria(Course.class)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.setFetchMode("listOpenCourse", FetchMode.EAGER)
				.list();
	}

	@SuppressWarnings("unchecked")
	public List<Course> findCourseByName(String courseName) {
		return sessionFactory.getCurrentSession()
				.createCriteria(Course.class)
				.add(Restrictions.like("courseName", "%" + courseName + "%"))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.list();
	}
	
	public void updateCourse(Course course) {
		sessionFactory.getCurrentSession().merge(course);
	}

	public void deleteCourse(Course course) {
		sessionFactory.getCurrentSession().delete(course);
	}

	public Course getCourseById(String courseId) {
		return (Course) sessionFactory.getCurrentSession()
				.createCriteria(Course.class)
				.add(Restrictions.eq("courseId", courseId))
				.setFetchMode("listOpenCourse", FetchMode.EAGER)
				.uniqueResult();
	}
}
